

let fs = require("fs");

let format = require("./format.js")

let dfsInfoFile = "C:/Program Files (x86)/Steam/steamapps/common/Dwarf Fortress/hack/raw/unitsInfo.js";
// let dfsInfoFile = "F:/st/steamapps/common/Dwarf Fortress/hack/raw/unitsInfo.js";
// let dfsInfoFile = "./unitsInfo.js";

// let dfsInfoFile = "F:/st/steamapps/common/Dwarf Fortress/text";




let cors = require("cors")
let express = require("express")
// 打包指令 pkg -t win index.js
// html 代码混淆 https://jshunxiao.com/
let open = require("child_process")

const app = express()

app.use(cors());
app.use(express.static('public'))


app.get('/api/dfData', async (req, res) => {
    let dfdatas = getDFs();
    res.send(dfdatas || []); 
})


app.listen(6018, () => {
    console.log("在浏览器中打开网址:http://localhost:6018")
    console.log("df中使用dfhack脚本 shenxian 的导出")
    open.exec("start http://localhost:6018")
})




function getDFs() {
    try {
        let fileStr = fs.readFileSync(dfsInfoFile).toString()
        if(fileStr) {
            let dfInfo = JSON.parse(fileStr)
            let fileArr = [];
            for (let id in dfInfo) {
                let dfdata = dfInfo[id]
                dfdata.id = id
                let jobArr = dfdata.jobSkill.trim().split(" ")
                // skill
                dfdata.jobSkill = {}
                jobArr.forEach((v, i) => {
                    let value = v-0;
                    let skillName = format.skillEnums[i][0];
                    let skillType = format.skillEnums[i][2];
                    if(!dfdata.jobSkill[skillType]){
                        dfdata.jobSkill[skillType] = {}
                    }
                    dfdata.jobSkill[skillType][skillName] = value
                });
                // items
                let items = dfdata.items.trim().split(";");
                items = items.filter(v => v && v != "")
                dfdata.items = items;
                // emo
                let emoLogs = dfdata.emoStr.trim().split("&").filter(v=>v&&v!="");
                emoLogs = emoLogs.map(v => {
                    let [type, thought, year, yeartick,strength,severity,flags] = v.split(";");
                    let emoInfo = {
                        type: format.emotion_type[type],
                        strength,severity,
                        value: format.emotion_type_value[format.emotion_type[type]],
                        thought: format.unit_thought_type[thought],
                        year: year-0,
                        yeartick: yeartick-0,
                        flags: flags?.split(",").filter(v=>v)
                    }
                    return emoInfo
                });
                emoLogs = emoLogs.sort((b,a)=> a.year-b.year || a.yeartick-b.yeartick )
                dfdata.emoStr = emoLogs;



                fileArr.push(dfdata)
            }
            return fileArr
        }
    } catch (error) {
        console.log(error);
    }
    
}
